package com.wzqj.agent.app.login.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wzqj.agent.app.user.domain.AppToken;
import com.wzqj.agent.app.user.domain.UserInfo;
import com.wzqj.agent.app.user.service.ApiUserService;
import com.wzqj.agent.common.JsonOutput;
import com.wzqj.agent.common.Log;
import com.wzqj.agent.common.constant.ErrConstant;
import com.wzqj.agent.common.env.EnvManager;
import com.wzqj.agent.common.exception.BusinessErrorType;
import com.wzqj.agent.common.redis.CacheClient;
import com.wzqj.agent.common.redis.CacheKey;
import com.wzqj.agent.util.CaptchaUtil;
import com.wzqj.agent.util.SmsSOA;
import com.wzqj.agent.util.TokenUtil;
import com.wzqj.agent.util.ValidateUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.UnsupportedEncodingException;

/**
 * Created by wanghao@weipass.cn on 2015/7/31.
 */
@Controller
@RequestMapping("/api/login")
public class ApiLoginController {

    @Autowired
    private CacheClient cacheClient;

    @Autowired
    private ApiUserService apiUserService;

    /**
     * 万能验证码
     */
    private static final String UNIVERSAL_CAPTCHA = "0923";
    /**
     * 校验登录
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/checkLogin")
    @ResponseBody
    public JSONObject checkLogin(HttpServletRequest request, HttpServletResponse response){

        JsonOutput output = new JsonOutput();
        String errCode = request.getParameter("errCode");
        long err = Long.parseLong(errCode);
        if(err == ErrConstant.ERRCODE_CHECKLOGIN_FAIL){
            output.setErrCode(BusinessErrorType.NOT_LOGIN.getErrCode());
            output.setMsg(BusinessErrorType.NOT_LOGIN.getErrMsg());
        }else if(err == ErrConstant.ERRCODE_TOKEN_INVALID){
            output.setErrCode(BusinessErrorType.TOKEN_INVALID.getErrCode());
            output.setMsg(BusinessErrorType.TOKEN_INVALID.getErrMsg());
        }
        return output.toJSONObject();
    }

    /**
     * 获取业务员登录验证码
     * @return
     */
    @RequestMapping("/captcha")
    @ResponseBody
    public JSONObject getCaptcha(String phone){

    	JSONObject data = new JSONObject();
    	
        JsonOutput output = new JsonOutput();
        if(!ValidateUtil.isMobile(phone)){
            output.setErrCode(BusinessErrorType.PARAM_ERROR.getErrCode());
            output.setMsg(BusinessErrorType.PARAM_ERROR.getErrMsg());
            return output.toJSONObject();
        }
        /**
         * 生成验证码
         */
        String captcha = CaptchaUtil.createCaptcha();//redis 缓存验证码有效期，5分钟
        Log.run.info("ApiLoginController#getCaptcha:验证码是：" + captcha);
        try {
            cacheClient.setex(CacheKey.用户登录验证码 + phone, 60 * 5, captcha);
        } catch (Exception e) {
            Log.run.error("ApiLoginController#getCaptcha:" + e.getMessage());
            output.setErrCode(BusinessErrorType.SOA_SEND_MSG_FAILURE.getErrCode());
            output.setMsg(BusinessErrorType.SOA_SEND_MSG_FAILURE.getErrMsg());
            return output.toJSONObject();
        }
        if (EnvManager.isIdc()) {
			
	        StringBuffer buffer = new StringBuffer();
	        buffer.append("【作业APP】 您的登录验证码是：").append(captcha).append("[微智全景]");
	        boolean flag = SmsSOA.sendSms(phone, buffer.toString());
	        if(!flag){
	            output.setErrCode(BusinessErrorType.SOA_SEND_MSG_FAILURE.getErrCode());
	            output.setMsg(BusinessErrorType.SOA_SEND_MSG_FAILURE.getErrMsg());
	            return output.toJSONObject();
	        }
        }else {
        	 data.put("captcha", captcha) ;
		}
        //data.put("captcha", captcha) ;
        output.setData(data);
        return output.toJSONObject();
    }

    /**
     * 获取登录token和用户信息
     * @return
     */
    @RequestMapping("/getToken")
    @ResponseBody
    public JSONObject getToken(String phone,String captcha,String mk,String mt) {

        JsonOutput output = new JsonOutput();
        if(!ValidateUtil.isMobile(phone) || !ValidateUtil.isCaptcha(captcha) || !ValidateUtil.isMt(mt) || null == mk){
            output.setErrCode(BusinessErrorType.PARAM_ERROR.getErrCode());
            output.setMsg(BusinessErrorType.PARAM_ERROR.getErrMsg());
            return output.toJSONObject();
        }
        Object captchaCache = null;
        try {
            captchaCache = cacheClient.get(CacheKey.用户登录验证码 + phone);
        } catch (Exception e) {
            output.setErrCode(BusinessErrorType.PARAM_ERROR.getErrCode());
            output.setMsg(BusinessErrorType.PARAM_ERROR.getErrMsg());
            return output.toJSONObject();
        }
        
        if(captcha.equals(UNIVERSAL_CAPTCHA)){//如果验证码为万能验证码
        	//验证通过对参数加密返回token对象和用户信息
            AppToken appToken = new AppToken();
            appToken.setWid(phone);
            appToken.setMk(mk);
            appToken.setMt(mt);
            appToken.setCreateTime(System.currentTimeMillis());
            try {
                UserInfo userInfo = apiUserService.getUserInfo(phone);
                if(userInfo != null && userInfo.getStatus() == 1){//用户存在且是正常状态
                    String tokenStr = TokenUtil.tokenToStr(appToken);
                    cacheClient.del(CacheKey.用户令牌 + phone);
                    long setnx = cacheClient.setnx(CacheKey.用户令牌 + phone, tokenStr);
                    if(setnx == 1){//成功
                        JSONObject data = new JSONObject();
                        JSONObject user = (JSONObject) JSON.toJSON(userInfo);
                        data.put("token",tokenStr);
                        data.put("wid",phone);
                        data.put("mt",mt);
                        data.put("mk",mk);
                        data.put("userInfo",user);
                        output.setData(data);
                    }else{//失败
                        output.setErrCode(BusinessErrorType.LOGIN_TOKEN_GENE_ERROR.getErrCode());
                        output.setMsg(BusinessErrorType.LOGIN_TOKEN_GENE_ERROR.getErrMsg());
                    }
                }else{
                    output.setErrCode(BusinessErrorType.LOGIN_TOKEN_GENE_ERROR.getErrCode());
                    output.setMsg(BusinessErrorType.LOGIN_TOKEN_GENE_ERROR.getErrMsg());
                    return output.toJSONObject();
                }
            } catch (UnsupportedEncodingException e) {
                output.setErrCode(BusinessErrorType.LOGIN_TOKEN_GENE_ERROR.getErrCode());
                output.setMsg(BusinessErrorType.LOGIN_TOKEN_GENE_ERROR.getErrMsg());
                Log.run.error("AppLoginController#getToken:" + e.getMessage());
            }
        }else{//若不是万能验证码
	        if(null == captchaCache){//验证码已过期
	            output.setErrCode(BusinessErrorType.LOGIN_CAPTCHA_INVALID.getErrCode());
	            output.setMsg(BusinessErrorType.LOGIN_CAPTCHA_INVALID.getErrMsg());
	        }else if(!captchaCache.equals(captcha)){//验证码不正确
	            output.setErrCode(BusinessErrorType.LOGIN_CAPTCHA_ERROR.getErrCode());
	            output.setMsg(BusinessErrorType.LOGIN_CAPTCHA_ERROR.getErrMsg());
	        }else{//验证通过对参数加密返回token对象和用户信息
	            AppToken appToken = new AppToken();
	            appToken.setWid(phone);
	            appToken.setMk(mk);
	            appToken.setMt(mt);
	            appToken.setCreateTime(System.currentTimeMillis());
	            try {
	                UserInfo userInfo = apiUserService.getUserInfo(phone);
	                if(userInfo != null && userInfo.getStatus() == 1){//用户存在且是正常状态
	                    String tokenStr = TokenUtil.tokenToStr(appToken);
	                    cacheClient.del(CacheKey.用户令牌 + phone);
	                    long setnx = cacheClient.setnx(CacheKey.用户令牌 + phone, tokenStr);
	                    if(setnx == 1){//成功
	                        JSONObject data = new JSONObject();
	                        JSONObject user = (JSONObject) JSON.toJSON(userInfo);
	                        data.put("token",tokenStr);
	                        data.put("wid",phone);
	                        data.put("mt",mt);
	                        data.put("mk",mk);
	                        data.put("userInfo",user);
	                        output.setData(data);
	                    }else{//失败
	                        output.setErrCode(BusinessErrorType.LOGIN_TOKEN_GENE_ERROR.getErrCode());
	                        output.setMsg(BusinessErrorType.LOGIN_TOKEN_GENE_ERROR.getErrMsg());
	                    }
	                }else{
	                    output.setErrCode(BusinessErrorType.LOGIN_TOKEN_GENE_ERROR.getErrCode());
	                    output.setMsg(BusinessErrorType.LOGIN_TOKEN_GENE_ERROR.getErrMsg());
	                    return output.toJSONObject();
	                }
	            } catch (UnsupportedEncodingException e) {
	                output.setErrCode(BusinessErrorType.LOGIN_TOKEN_GENE_ERROR.getErrCode());
	                output.setMsg(BusinessErrorType.LOGIN_TOKEN_GENE_ERROR.getErrMsg());
	                Log.run.error("AppLoginController#getToken:" + e.getMessage());
	            }
	        }
        }
        return output.toJSONObject();
    }

    /**
     * 登出
     * @return
     */
    @RequestMapping("/logout")
    @ResponseBody
    public JSONObject logout(String appToken){

        JsonOutput output = new JsonOutput();
        if(StringUtils.isEmpty(appToken)){
            output.setErrCode(BusinessErrorType.PARAM_ERROR.getErrCode());
            output.setMsg(BusinessErrorType.PARAM_ERROR.getErrMsg());
            return output.toJSONObject();
        }
        try {
            AppToken token = TokenUtil.strToToken(appToken);
            Object cache = cacheClient.get(CacheKey.用户令牌 + token.getWid());
            if(null != cache && appToken.equals(cache.toString())){
                cacheClient.del(CacheKey.用户令牌 + token.getWid());
                output.setMsg("登出成功");
            }else{
                output.setErrCode(BusinessErrorType.PARAM_ERROR.getErrCode());
                output.setMsg(BusinessErrorType.PARAM_ERROR.getErrMsg());
            }
        } catch (Exception e) {
            output.setErrCode(BusinessErrorType.LOGIN_TOKEN_DELETE_ERROR.getErrCode());
            output.setMsg(BusinessErrorType.LOGIN_TOKEN_DELETE_ERROR.getErrMsg());
        }
        return output.toJSONObject();
    }

}
